<?php
// 设置响应头
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// 处理预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// 只允许POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => '只允许POST请求']);
    exit();
}

try {
    // 获取POST数据
    $input = json_decode(file_get_contents('php://input'), true);
    
    // 验证必填字段
    if (empty($input['name']) || empty($input['email']) || empty($input['message'])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => '请填写所有必填字段']);
        exit();
    }
    
    // 验证邮箱格式
    if (!filter_var($input['email'], FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => '邮箱格式不正确']);
        exit();
    }
    
    // 获取客户端信息
    $clientIP = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    $timestamp = date('Y-m-d H:i:s');
    
    // 清理输入数据
    $name = htmlspecialchars(trim($input['name']), ENT_QUOTES, 'UTF-8');
    $email = htmlspecialchars(trim($input['email']), ENT_QUOTES, 'UTF-8');
    $message = htmlspecialchars(trim($input['message']), ENT_QUOTES, 'UTF-8');
    
    // 创建data目录（如果不存在）
    if (!is_dir('data')) {
        mkdir('data', 0755, true);
    }
    
    // 准备数据
    $contactData = [
        'timestamp' => $timestamp,
        'name' => $name,
        'email' => $email,
        'message' => $message,
        'clientIP' => $clientIP,
        'userAgent' => $userAgent
    ];
    
    // 1. 保存到可读格式文件 (data/contacts.txt)
    $readableFormat = "\n=== 联系表单提交 ===\n";
    $readableFormat .= "时间: {$timestamp}\n";
    $readableFormat .= "姓名: {$name}\n";
    $readableFormat .= "邮箱: {$email}\n";
    $readableFormat .= "消息: {$message}\n";
    $readableFormat .= "IP地址: {$clientIP}\n";
    $readableFormat .= "用户代理: {$userAgent}\n";
    $readableFormat .= "========================\n";
    
    file_put_contents('data/contacts.txt', $readableFormat, FILE_APPEND | LOCK_EX);
    
    // 2. 保存到JSON格式文件 (data/contacts.json)
    $jsonFile = 'data/contacts.json';
    $existingData = [];
    if (file_exists($jsonFile)) {
        $existingContent = file_get_contents($jsonFile);
        if (!empty($existingContent)) {
            $existingData = json_decode($existingContent, true) ?: [];
        }
    }
    $existingData[] = $contactData;
    file_put_contents($jsonFile, json_encode($existingData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), LOCK_EX);
    
    // 3. 追加到根目录的info.txt
    $infoContent = "[{$timestamp}] 联系表单 - 姓名: {$name}, 邮箱: {$email}, 消息: {$message}\n";
    file_put_contents('info.txt', $infoContent, FILE_APPEND | LOCK_EX);
    
    // 返回成功响应
    echo json_encode([
        'success' => true, 
        'message' => '感谢您的留言！我们会尽快回复您。',
        'timestamp' => $timestamp
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => '服务器错误，请稍后重试',
        'error' => $e->getMessage()
    ]);
}
?>